﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Xml;
using System.Data;
using Hydrobase;
using HydrobaseSDK;
using HydroBugger;
using WareForms;

using System.Windows.Forms;

namespace LoneWolf
{
    public class RssItemTreeView: TreeView 
    {
        RssFeed Feed;
        RssChannel mainchanel;
        List<RssItem> RssItemLst = new List<RssItem>();
        static List<RssFeedInfo> FeedList;
        public static DataSet RssInfo;
        private System.ComponentModel.IContainer components;
        hydrobaseADO ado = new hydrobaseADO();
      /*internal  static  string fileurlsfolder;
        public string DownloadedFilesDir
        {

            get { return fileurlsfolder; }
            set { fileurlsfolder = value; }
        }
        */
        public RssItemTreeView()
        {
            this.Enabled = true;
           

        }
      /// <summary>
      /// Fills the treeview withe the itesm taken from the feed
      /// </summary>
      /// <param name="feed">the rss item from the c</param>
      /// <param name="addtoFeedList">if its true it adds it sef in the list of 
      /// feed tht you  willwatch</param>
      /// <returns> The Rss feed</returns>
        public RssFeed  GetRssItemsOnlyfromMainchanel(string  feed,bool addtoFeedList)
        {

            try
            {
                RssFeed ap = null;
                if ((string.IsNullOrEmpty (feed)==false ) &&
                    (feed !=BaseClass.emptycellChar))
                {
                    WebClient webclient = new WebClient();

                   Stream  strm = webclient.OpenRead(feed);
                   

                   if (strm != null)
                   {
                       StreamReader reader = new StreamReader(strm);
                       string cont =reader.ReadToEnd();
                       if (string.IsNullOrEmpty(cont) == false)
                       {
                           //MessageBox.Show(cont);
                           Feed = RssFeed.FromText(cont);
                           if (addtoFeedList == true)
                           {
                               RssFeedInfo rsinf = new RssFeedInfo();
                               rsinf.RssFeed = Feed;
                             
                               rsinf.TorrentsSavePath = Feed.MainChannel.Title;
                               FeedList.Add(rsinf);
                               

                             if ((RssInfo != null) && (RssInfo.Tables.Count > 0) && (RssInfo.Tables[0] != null))
                               {
                                   object[] val = new object[RssInfo.Tables[0].Columns.Count];
                                   val[0] = feed;
                                   val[1] = rsinf.TorrentsSavePath;
                                   if (RssInfo.Tables[0].Rows.Contains(val[0]) != true)
                                   {
                                       RssInfo.Tables[0].Rows.Add(val);
                                   }

                               }

                               
                           }
                           else
                           {
                               ap = Feed;

                           }
                           if (Feed != null)
                           {
                               mainchanel = Feed.MainChannel;
                               //    MessageBox.Show(mainchanel.Title);

                               if (mainchanel != null)
                               {


                                   TreeNode rootnode = new TreeNode(mainchanel.Title);

                                   this.Nodes.Add(rootnode);

                                   foreach (RssItem rssitem in mainchanel.Items)
                                   {

                                       TreeNode rssitemnode = new TreeNode(rssitem.Title);
                                       RssItemLst.Add(rssitem);

                                       rootnode.Nodes.Add(rssitemnode);
                                      // 
                                       // tmp = rssitemnode;

                                   }


                                   this.ExpandAll();
                               }

                           }

                       }
                       this.Refresh();
                   }

                }

                return ap;
            }
            catch (Exception ex)
            {
                Core.errorreport(ex);
                return null;
            }
        }
        /// <summary>
        /// Fills the treeview withe the itesm taken from the feed
        /// </summary>
        /// <param name="feed">the rss item from the c</param>
        public void GetRssItems(string feed)
        {

            try
            {
                if (feed != null)
                {
                    Feed = RssFeed.FromUri(feed);
                    if (Feed != null)
                    {
                        foreach (RssChannel chanel in Feed.Channels)
                        {

                            if (chanel != null)
                            {
                                TreeNode rootnode = new TreeNode(chanel.Title);
                                foreach (RssItem rssitem in chanel.Items)
                                {
                                    TreeNode rssitemnode = new TreeNode(rssitem.Title);
                                    RssItemLst.Add(rssitem);
                                  //  rssitemnode.ContextMenuStrip = this.contextMenuStrip;
                                    rootnode.Nodes.Add(rssitemnode);


                                }
                                this.Nodes.Add(rootnode);
                            }


                        }
                    }

                }


            }
            catch (Exception ex)
            {
                Core.errorreport(ex);
            }
        }
        /// <summary>
        /// Searches through the rss item's collection the rssitem wth the given title
        /// and returns it
        /// </summary>
        /// <param name="title">the title that rss item you are searching for</param>
        /// <returns>Searches through the rss item's collection the rssitem wth the given title
        /// and returns it</returns>
        public RssItem  SearchRssItem(string title)
        {
            try
            {
                RssItem ap = null;
                if (string.IsNullOrEmpty(title) == false)
                {
                    foreach (RssItem item in RssItemLst)
                    {
                        if (item.Title == title)
                        {

                            ap = item;
                            break;
                        }

                    }


                }
                return ap;

            }
            catch (Exception ex)
            {
                Core.errorreport(ex);
                return null;
            }

        }

        /// <summary>
        /// Reads the feeds from the saved file
        /// </summary>
        public void LoadFeeds()
        {
            try
            {
                if (SDKBase.ApplicationPreferencesDir != null)
                {
                    FeedList = new List<RssFeedInfo>();
                    if (File.Exists(Path.Combine(SDKBase.ApplicationPreferencesDir, Core.Feedsfile)) == true)
                    {
                        RssInfo = new DataSet();
                        ado.AttachDataBaseinDataSet(RssInfo, Path.Combine(SDKBase.ApplicationPreferencesDir, Core.Feedsfile));
                        if ((RssInfo != null) &&(RssInfo.Tables.Count>0 ) &&(RssInfo.Tables[0] !=null))
                        {
                            DataTable table = RssInfo.Tables[0];
                           
                            foreach(DataRow row in table.Rows)
                            {
                            object[] vals = row.ItemArray;
                              RssFeed rssfeed= this.GetRssItemsOnlyfromMainchanel(Convert.ToString(vals[0]),true );
                               



                                
                            }

                            


                        }

                    }

                }
                
            }
            catch (Exception ex)
            {
                Core.errorreport(ex);
                
            }



        }
        /// <summary>
        /// saves  the feeds 
        /// </summary>
        public void SaveFeeds()
        {
            try
            {
                if (SDKBase.ApplicationPreferencesDir != null)
                {

                    if (File.Exists(Path.Combine(SDKBase.ApplicationPreferencesDir, Core.Feedsfile)) == true)
                    {

                        
                        if ((RssInfo != null) && (RssInfo.Tables.Count > 0) && (RssInfo.Tables[0] != null))
                        {



                            ado.SaveTable(RssInfo, Path.Combine(SDKBase.ApplicationPreferencesDir, Core.Feedsfile), 0, Application.ProductName + "-" + Application.ProductVersion);





                        }

                    }

                }

            }
            catch (Exception ex)
            {
                Core.errorreport(ex);

            }



        }

        /// <summary>
        /// Search the existed feed list for
        /// the existant of a feed with a mainchannel's title 
        /// the given arument and returns
        /// </summary>
        /// <param name="mainchanelstitle"></param>
        /// <returns></returns>
        public RssFeedInfo SearchFeed(string mainchanelstitle)
        {
            try
            {
                RssFeedInfo ap = null;

                if (string.IsNullOrEmpty(mainchanelstitle) == false)
                {

                    foreach (RssFeedInfo infitem in FeedList)
                    {
                        if(infitem.RssFeed.MainChannel.Title==mainchanelstitle)
                        {
                            ap = infitem;
                            break;
                        }

                    }
                }

                return ap;
            }
            catch (Exception ex)
            {
                Core.errorreport(ex);
                return null;

            }


        }
        /// <summary>
        /// Returns the collection of rssitems;
        /// </summary>
        public List<RssItem> RssItemList
        {
            
            get { return RssItemLst; }

           
        }

        
        public List<RssFeedInfo> Feeds
        {
            get { return FeedList; }

        }
        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // RssItemTreeView
            // 
            this.Dock = System.Windows.Forms.DockStyle.Fill;
            this.ShowNodeToolTips = true;
            this.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.RssItemTreeView_NodeMouseClick);
            this.ResumeLayout(false);

        }

        
     
        #region events
      

        
        #endregion

        private void RssItemTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Left)
                {

                    //this.ContextMenu.Show(this, e.Location);
                  //  this.contextMenuStrip.Show(e.Location);


                }

            }
            catch (Exception ex)
            {
                Core.errorreport(ex);

            }
        }

       
       
    }
}
